<template>
    <div>
      <n-card>
        <n-form
            ref="formRef"
            inline
            :label-width="400"
        >
          <n-form-item label="资源类型" path="queryForm.name" :show-label="false">
            <n-select :options="remoteResourceType" style="width: 200px;" placeholder="资源名称">
            </n-select>
          </n-form-item>
          <n-form-item label="资源名称" path="queryForm.name" :show-label="false">
            <n-input   placeholder="请输入资源名称" v-model:value="queryForm.name" />
          </n-form-item>
          <n-form-item :show-label="false">
            <n-space justify="end">
              <n-button @click="getDataList" type="primary">查询</n-button>
            </n-space>
          </n-form-item>
        </n-form>

      </n-card>
      <n-card style="margin-top: 5px">
        <n-space style="margin-bottom: 10px;" justify="space-between">

          <n-dropdown :options="dropdownOptions"  placement="bottom-start" trigger="click" size="small" @select="handAddSelect">
            <n-button type="primary">新增</n-button>
          </n-dropdown>

          <n-button type="info" @click="refreshCache">刷新缓存</n-button>
        </n-space>
        <n-data-table
            :loading="tableLoading"
            :columns="resourceColumns"
            :data="resourceInfo"
        />
      </n-card>
      <editSDForm ref="editSDFormRef"/>
      <editMjForm ref="editMjFormRef"/>
      <editChatGPTForm ref="editChatGPTFormRef"/>
      <editBDTranslateForm ref="editBDTranslateFormRef"/>
      <editAzureSpeechForm ref="editAzureSpeechFormRef"/>
      <editFooocusForm ref="editFooocusFormRef"></editFooocusForm>
      <n-drawer v-model:show="modelManagerShow" :width="1000">
        <n-drawer-content title="模型管理" closable>
          <ModelManager :resourceId="selectdResourceId"/>
        </n-drawer-content>
      </n-drawer>
    </div>
</template>

<script lang="ts" setup>
import {h, reactive, ref, onMounted, Component, watch} from 'vue'
import { NTag, NButton } from 'naive-ui'
import {resourceController} from '@/api/resource/resourceController.api'
import editSDForm from "@/views/resource/form/editSDForm.vue"
import editMjForm from '@/views/resource/form/mjEditForm.vue'
import editChatGPTForm from '@/views/resource/form/editChatGPTForm.vue'
import editBDTranslateForm from '@/views/resource/form/editBDTranslateForm.vue'
import editAzureSpeechForm from '@/views/resource/form/editAzureSpeechForm.vue'
import editFooocusForm from "@/views/resource/form/editFooocusForm.vue";
import {remoteResourceType} from '@/views/resource/index'
import {mjControllerApi} from "@/api/mj/mjController.api";
import ModelManager from '@/views/pages/aiart/stablediffusion/modelManager.vue'

const editSDFormRef = ref(null)
const editMjFormRef = ref(null)
const editChatGPTFormRef = ref(null)
const editBDTranslateFormRef = ref(null)
const editAzureSpeechFormRef = ref(null)
const editFooocusFormRef = ref(null)

const tableLoading = ref(false)
const resourceInfo = ref([])
const modelManagerShow = ref(false)
const selectdResourceId = ref('')


const queryForm = reactive({
  type:'',
  name:''
})

const dropdownOptions = [
  {
    label: 'Stable Diffusion',
    key: 'SD'
  },
  {
    label: 'Midjourney',
    key: 'MJ'
  },
  {
    label: 'Fooocus',
    key: 'Fooocus'
  },
  // {
  //   label: 'Azure TTS',
  //   key: 'AzureTTS'
  // },
  {
    label: '百度翻译',
    key: 'BDTranslate'
  }
  // , {
  //   label: 'ChatGPT',
  //   key:'ChatGPT'
  // }
]

const resourceColumns  = [

  {
    title: '#',
    key: 'key',
    render: (row,index) => {
      return `${index + 1}`
    }
  },
  {
    title: '资源类型',
    key:'type',
    render:(row:any) =>{
      return h(
          NTag,
          {
            style: {
              marginRight: '6px'
            },
            type:'info',
          },
          {
            default:() => row.obj.type
          }
      )
    }
  },
  {
    title: '资源名称',
    key:'name'
  },
  {
    title: '是否公开',
    key: 'isPublic',
    render(row) {
      if(row.isPublic === '1'){
        return h(
            NTag,
            {
              style: {
                marginRight: '6px'
              },
              type: 'info',
              bordered: false
            },
            {
              default: () => '公开'
            }
        )
      }else{
        return h(
            NTag,
            {
              style: {
                marginRight: '6px'
              },
              type: 'error',
              bordered: false
            },
            {
              default: () => '私有'
            }
        )
      }
    }
  },
  {
    title: '状态',
    key:'status',
    render (row) {
      if(row.status === '1'){
        return h(
              NTag,
              {
                style: {
                  marginRight: '6px'
                },
                type: 'info',
                bordered: false
              },
              {
                default: () => '正常'
              }
          )
      }else if(row.status === '0'){
        return h(
            NTag,
            {
              style: {
                marginRight: '6px'
              },
              type: 'error',
              bordered: false
            },
            {
              default: () => '无法连接'
            }
        )
      }else if(row.status==='2'){
        return h(
            NTag,
            {
              style: {
                marginRight: '6px'
              },
              type: 'warning',
              bordered: false
            },
            {
              default: () => '停用'
            }
        )
      }
      return row.status
    }
  },
  {
    title: '资源地址',
    key: 'address'
  },
  {
    title: '默认',
    key: 'isDefault',
    render (row) {
      if (row.isDefault === '1') {
        return h(
            NTag,
            {
              style: {
                marginRight: '6px'
              },
              type: 'info',
              bordered: false
            },
            {
              default: () => '默认选项'
            }
        )
      }
    }
  },
  {
    title: '操作',
    key: 'actions',
    render(row) {
      const buttons = [h(
          NButton,
          {
            size: 'small',
            type: 'info',
            onClick:()=> resourceEdit(row)
          },
          {default: () => '编辑'}
      ),h(
          NButton,
          {
            size: 'small',
            type: 'warning',
            style: 'margin-left:5px',
            onClick:()=> resourceDeleteById(row)
          },
          {default: () => '删除'}
      ),h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            style: 'margin-left:5px',
            loading: row.loading,
            onClick:()=> resourceTest(row)
          },
          {default: () => '测试'}
      ) ]
      if (row.type === 'SD' ) {
        buttons.push(h(
            NButton,
            {
              size: 'small',
              type: 'warning',
              style: 'margin-left:5px',
              onClick:()=> {
                selectdResourceId.value = row.id
                console.log(selectdResourceId.value)
                modelManagerShow.value = true
              }
            },
            {default: () => '模型配置'}
        ))
      }
      return buttons;
    }
  }
]

const handAddSelect = (key:string) => {
  if(key ==='SD'){
    editSDFormRef?.value?.onAdd()
  }else if(key === 'MJ'){
    editMjFormRef?.value?.onAdd()
  }else if(key ==='ChatGPT'){
    editChatGPTFormRef?.value?.onAdd()
  }else if(key === 'BDTranslate' ){
    editBDTranslateFormRef?.value?.onAdd()
  }else if(key==='AzureTTS'){
    editAzureSpeechFormRef?.value?.onAdd()
  }else if(key==='Fooocus'){
    editFooocusFormRef?.value?.onAdd()
  }
}

const resourceEdit = (row:any) =>{
  if(row.type === 'SD'){
    editSDFormRef?.value?.onEdit(row.obj)
  }else if(row.type==='ChatGPT'){
    editChatGPTFormRef?.value?.onEdit(row.obj)
  }else if(row.type === "MJ"){
    editMjFormRef?.value?.onEdit(row.obj)
  }else if(row.type ==="AzureTTS"){
    editAzureSpeechFormRef?.value?.onEdit(row.obj)
  }else if(row.type ==="DBTranslate"){
    editBDTranslateFormRef?.value?.onEdit(row.obj)
  }else if(row.type==='Fooocus'){
    editFooocusFormRef?.value?.onEdit(row.obj)
  }
}
const resourceDeleteById = (row:any) => {
  window.$dialog.error({
    title: "温馨提醒",
    content: "删除操作不可逆，是否继续？",
    positiveText: "确定",
    negativeText: "取消",
    onPositiveClick: () => {
      resourceController.deleteResource(row.id).then((res:any) =>{
        if(res.code === 200){
          getDataList()
        }
      })
    }
  })
}

const resourceTest = (row:any)=>{
  if(row.type != 'SD' && row.type!='ChatGPT' && row.type !='Fooocus' && row.type !='MJ'){
    window.$message.warning("暂不支持测试")
    return
  }
  if(row.type ==='MJ'){
    row.loading = true
    mjControllerApi.reConnect().then((res:any) =>{
      if(res.code === 200){
        window.$message.success("连接中,请稍后!")
      }
    }).finally(()=>{
      row.loading = false
    })
  }else {
    row.loading = true
    resourceController.resourceTest(row.id).then((res: any) => {
      if (res.code === 200) {
        window.$message.success("连接成功!")
      } else {
        window.$message.error(res.msg)
      }
    }).finally(() => {
      row.loading = false
    })
  }
}


/**
 * 获取列表数据
 * @param data
 */
const getDataList = () => {
  tableLoading.value = true
  resourceController.getRemoteResourceInfo(queryForm).then((res: any) => {
    tableLoading.value = false
    console.log(res)
    if(res.code === 200){
      resourceInfo.value = res.data
    }
  }).catch((e: any) => {
    tableLoading.value = true
  })
}

const refreshCache = () =>{
  resourceController.refreshCache().then((res:any) =>{
    if(res.code === 200){
      window.$message.success(res.msg)
    }
  })
}


watch(() => editSDFormRef?.value?.modalLoading, () => getDataList(), {deep: true})
watch(() => editMjFormRef?.value?.modalLoading, () => getDataList(), {deep: true})
watch(() => editChatGPTFormRef?.value?.modalLoading, () => getDataList(), {deep: true})
watch(() => editBDTranslateFormRef?.value?.modalLoading, () => getDataList(), {deep: true})
watch(() => editAzureSpeechFormRef?.value?.modalLoading, () => getDataList(), {deep: true})
watch(() => editFooocusFormRef?.value?.modalLoading, () => getDataList(), {deep: true})


const modalShow = () =>{
  editSDFormRef?.value?.onAdd()
}

onMounted(()=>{
  getDataList()
})
</script>
